<?php

namespace apiend\models\upload;

use Yii;
use common\helpers\FileHelper;
use common\helpers\IpHelper;
use common\models\Attachment;
use yii\web\UploadedFile;
use yii\base\Exception;

/**
 * 文件上传模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class FileUploadModel extends \common\base\Model {

    const SCOPE_DEFAULT = 'default';
    const SCOPE_FILES = 'files';
    const SCOPE_USER = 'user';
    const SCOPE_AUTHENT = 'authent';

    /**
     * @var integer 用户UID
     */
    public $user_id = 0;

    /**
     * @var string 应用范围
     */
    public $scope = 'files';

    /**
     * @var UploadedFile file attribute
     */
    public $file = null;

    /**
     * @var string 上传通道,支持通道:阿里云OSS、服务器SFTP
     */
    public $channel = Attachment::CHANNEL_ID_OSS;

    /**
     * @var integer 是否启用图片压缩
     */
    public $cut = 0;

    /**
     * @var string 上传根目录别名
     */
    public $uploadPath = '@uploads';

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            [['user_id'], 'integer'],
            ['scope', 'in', 'range' => static::getConstants(), 'message' => '{attribute}不在允许范围内'],
            [['file'], 'file'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'user_id' => '用户ID',
            'scope' => '应用场景',
            'file' => '文件',
        ];
    }

    /**
     * @inheritdoc
     */
    public function upload() {
        if (!$this->validate()) {
            $this->dumpError('上传校验失败', $this->getFirstErrors());
        }

        $relativeDir = '/attachments/' . $this->scope . '/' . date('Ym/d') . '/';
        $absoluteDir = Yii::getAlias($this->uploadPath . $relativeDir);
        FileHelper::dirCreate($absoluteDir);

        $file = $this->file;
        $extension = $file->extension;

        $filename = FileHelper::buildUploadFileName($extension);

        $file->saveAs($absoluteDir . $filename);

        $relativePath = $relativeDir . $filename;

        if ($file->getHasError()) {
            $this->dumpError('文件保存失败', $file->error);
        }
        $attachs = new Attachment();
        $attachs->attributes = [
            'user_id' => $this->user_id,
            'path' => $relativePath,
            'original_name' => $file->name,
            'channel_id' => $this->channel,
            'size' => $file->size,
            'format' => 1,
            'ip' => IpHelper::ip(),
        ];
        $attachs->generateToken();
        if (!$attachs->save()) {
            return $attachs->dumpError();
        }
        return $attachs->toArray();
    }

}
